<template>
  <r-header />
  <div class="page">
    <div class="top">
      <P>商品列表</P>
      <div class="txt">充值立即到账，如有疑问请联系客服。</div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>正在加载商品...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
      <button @click="refreshProducts" class="retry-btn">重试</button>
    </div>
    
    <!-- 商品列表 -->
    <div v-else-if="products.length > 0" class="products-container">
      <div class="card" v-for="product in products" :key="product.id">
        <div class="product-info">
          <div class="product-details">
            <h3 class="product-name">{{ product.name }}</h3>
            <p class="product-description">{{ formatDescription(product.description) }}</p>
            <div class="product-meta">
              <span class="product-type">{{ getProductTypeText(product.type) }}</span>
              <span v-if="product.token === -1" class="chat-count unlimited">无限制对话</span>
              <span v-else class="chat-count">包含 {{ product.token }} 次对话</span>
              <span v-if="product.validityDays" class="validity">有效期 {{ product.validityDays }} 天</span>
            </div>
            <div class="features">
              <div v-for="feature in features" :key="feature" class="feature-item">
                <img class="tick" src="/assets/对号.png" alt="✓">
                <span>{{ feature }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="purchase-section">
          <div class="price-info">
            <div class="current-price">¥{{ parseFloat(product.price).toFixed(2) }}</div>
            <div v-if="product.originalPrice" class="original-price">
              原价 ¥{{ parseFloat(product.originalPrice).toFixed(2) }}
            </div>
          </div>
          <div class="payment-methods">
            <span>支持支付宝、微信支付</span>
          </div>
          <button 
            @click="buyProduct(product)" 
            class="buy-btn"
            :disabled="!isLoggedIn"
          >
            {{ isLoggedIn ? '立即购买' : '请先登录' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty">
      <p>暂无商品</p>
      <button @click="refreshProducts" class="retry-btn">刷新</button>
    </div>
  </div>
</template>

<script type="text/javascript">
import { productApi, orderApi } from '@/api/product'

export default {
  name: "shop",
  data() {
    return {
      loading: false,
      products: [],
      error: null,
      features: [
        "全平台畅快浏览",
        "快速客服响应", 
        "全平台客户端",
        "即开即用",
      ]
    }
  },
  computed: {
    // 检查用户是否已登录
    isLoggedIn() {
      return this.$store.state.user.profile.islogin
    }
  },
  methods: {
    // 获取商品列表
    async loadProducts() {
      this.loading = true;
      this.error = null;
      
      try {
        console.log('开始加载商品列表...');
        const response = await productApi.getProducts();
        
        if (response.success) {
          this.products = response.data || [];
          console.log('商品列表加载成功:', this.products);
        } else {
          this.error = response.message || '获取商品列表失败';
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.error = '网络错误，请检查网络连接后重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 购买商品
    async buyProduct(product) {
      // 检查登录状态
      if (!this.isLoggedIn) {
        alert('请先登录后再购买商品');
        this.$router.push('/signin');
        return;
      }
      
      try {
        // 获取用户ID（优先使用数据库ID，如果没有则使用手机号）
        const userId = this.$store.state.user.profile.id || this.$store.state.user.profile.phone_number;
        
        console.log('当前用户信息:', this.$store.state.user.profile);
        console.log('使用的用户ID:', userId, '类型:', typeof userId);
        
        if (!userId) {
          alert('用户信息不完整，请重新登录');
          this.$router.push('/signin');
          return;
        }
        
        // 创建订单
        const orderData = {
          items: [{
            productId: product.id,
            quantity: 1
          }],
          remark: `购买商品：${product.name}`,
          userId: userId // 直接传递用户ID
        };
        
        console.log('创建订单:', orderData);
        const response = await orderApi.createOrder(orderData);
        
        if (response.success) {
          const order = response.data;
          console.log('订单创建成功:', order);
          
          // 跳转到支付页面，传递订单信息
          this.$router.push({
            path: '/pay',
            query: { 
              orderId: order.id,
              productName: product.name,
              amount: order.totalAmount
            }
          });
        } else {
          alert('创建订单失败：' + response.message);
        }
      } catch (error) {
        console.error('购买商品失败:', error);
        if (error.response?.data?.message) {
          alert('购买失败：' + error.response.data.message);
        } else {
          alert('购买失败，请稍后重试');
        }
      }
    },
    
    // 刷新商品列表
    refreshProducts() {
      this.loadProducts();
    },
    
    
    // 格式化商品描述
    formatDescription(description) {
      if (!description) return '暂无描述';
      return description.length > 100 ? description.substring(0, 100) + '...' : description;
    },
    
    // 获取商品类型显示文本
    getProductTypeText(type) {
      const typeMap = {
        'chat_package': '聊天套餐',
        'membership': '会员服务',
        'enterprise': '企业版'
      }
      return typeMap[type] || '其他'
    }
  },
  mounted() {
    this.loadProducts();
  }
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 90px 2rem 0;
  padding-top: 70px; // 为固定导航栏留出空间
  min-height: 100vh;
}

.top {
  margin-top: 18px;
  width: 100%;
  align-items: flex-start;
  font-weight: bold;
  font-size: 30px;
  color: #ffffff;

  .txt {
    margin: 21px 0 0;
    font-size: 14px;
    color: #7c91a3;
    font-weight: 400;
  }
}

@media screen and (min-width:660px) {
  .top {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

.products-container {
  width: 100%;
  max-width: 1200px;
}

.card {
  width: 100%;
  margin: 2rem 0;
  padding: 2rem;
  border: 1px solid #ffffff;
  border-radius: 15px;
  background: radial-gradient(164.75% 100% at 50% 0%, #334155 0%, #0F172A 48.73%);
  color: #7c91a3;
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.product-info {
  display: flex;
  gap: 2rem;
  align-items: flex-start;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 1rem;
}

.product-description {
  color: #9ca3af;
  margin-bottom: 1rem;
  line-height: 1.5;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 1rem;
  
  .product-type {
    background: #3b82f6;
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 12px;
    font-size: 12px;
  }
  
  .chat-count {
    color: #10b981;
    font-weight: bold;
    
    &.unlimited {
      color: #f59e0b;
    }
  }
  
  .validity {
    color: #6b7280;
    font-size: 14px;
  }
}

.features {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  
  .tick {
    width: 16px;
    height: 16px;
  }
  
  span {
    font-size: 14px;
    color: #9ca3af;
  }
}

.purchase-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
  border: 1px solid #374151;
  border-radius: 15px;
  background: rgba(31, 41, 55, 0.5);
}

.price-info {
  text-align: center;
  margin-bottom: 1rem;
  
  .current-price {
    font-size: 32px;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 0.5rem;
  }
  
  .original-price {
    color: #9ca3af;
    text-decoration: line-through;
    font-size: 16px;
  }
}

.payment-methods {
  color: #9ca3af;
  font-size: 14px;
  margin-bottom: 2rem;
}

.buy-btn {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  color: white;
  border: none;
  padding: 1rem 3rem;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #2563eb, #1e40af);
    transform: translateY(-2px);
    box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
  }
  
  &:disabled {
    background: #6b7280;
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  color: #ffffff;
  font-size: 18px;
  margin: 2rem 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #374151;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error, .empty {
  text-align: center;
  color: #ffffff;
  font-size: 18px;
  margin: 2rem 0;
}

.retry-btn {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  margin-top: 1rem;
  
  &:hover {
    background: #2563eb;
  }
}

@media screen and (min-width: 768px) {
  .card {
    flex-direction: row;
    align-items: center;
  }
  
  .purchase-section {
    min-width: 300px;
    margin-left: 2rem;
  }
}
</style>
